//
//  UIView+Extension.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/18.
//

import UIKit
import SnapKit

final class IntroViewController: UIViewController, UICollectionViewDelegate {

    // MARK: - Properties

    var didFinishIntro: (() -> Void)?

    private var currentIndex = 0
    
    private let totalPages = 2

    private lazy var collectionView: BTEBaseCollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = UIScreen.main.bounds.size

        let cv = BTEBaseCollectionView(frame: .zero, collectionViewLayout: layout)
        cv.isPagingEnabled = true
        cv.contentInset = .zero
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.bounces = false
        cv.dataSource = self
        cv.delegate = self
        cv.register(IntroPageCell.self, forCellWithReuseIdentifier: IntroPageCell.reuseIdentifier)
        return cv
    }()

    private var actionButton: UIButton = UIButton()

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupViews()
    }

    // MARK: - Setup

    private func setupViews() {
        actionButton.setTitle(title: BTELanguageManager.shared.localizedString(forKey: "Next"))
        actionButton.setBackgroundColor(UIColor.colorWithHex("#39B4E6")!)
        actionButton.roundCorners(.allCorners, radius: 25)
        actionButton.layer.borderColor = UIColor.colorWithHex("#6C2724")!.cgColor
        actionButton.layer.borderWidth = 3
        actionButton.addTarget(self, action: #selector(handleActionButtonTapped), for: .touchUpInside)
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        view.addSubview(actionButton)
        actionButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(38)
            make.height.equalTo(50)
            make.bottom.equalToSuperview().offset(-44)
        }
    }

    // MARK: - Actions

    @objc private func handleActionButtonTapped() {
        let nextIndex = currentIndex + 1
        guard nextIndex < totalPages else {
            didFinishIntro?()
            return
        }

        collectionView.scrollToItem(at: IndexPath(item: nextIndex, section: 0), at: .left, animated: true)
        currentIndex = nextIndex
        updateButtonTitle()
    }

    // MARK: - Helpers

    private func updateButtonTitle() {
        let isLastPage = currentIndex == totalPages - 1
        let titleKey = isLastPage ? "Start" : "Next"
        actionButton.setTitle(title: BTELanguageManager.shared.localizedString(forKey: titleKey))
    }

    private func updateCurrentIndex() {
        let page = Int(collectionView.contentOffset.x / UIScreen.main.bounds.width)
        currentIndex = page
        updateButtonTitle()
    }
}

// MARK: - UICollectionViewDataSource

extension IntroViewController: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int { 1 }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return totalPages
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IntroPageCell.reuseIdentifier, for: indexPath) as? IntroPageCell else {
            return UICollectionViewCell()
        }

        let imageName = indexPath.item == 0
            ? BTELanguageManager.shared.localizedImageString(forKey: "Group 117127733622222222")
            : BTELanguageManager.shared.localizedImageString(forKey: "Group 1171277337ffffff")

        cell.imageName = imageName
        return cell
    }
}

// MARK: - UIScrollViewDelegate

extension IntroViewController: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        updateCurrentIndex()
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        updateCurrentIndex()
    }
}


class IntroPageCell: UICollectionViewCell {

    static let reuseIdentifier = "IntroPageCell"

    private let imageView = UIImageView()

    var imageName: String? {
        didSet {
            imageView.image = UIImage(named: imageName ?? "")
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
